package com.stylefeng.guns.modular.stuinfo.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.LoginLog;
import com.stylefeng.guns.modular.system.warpper.LogWarpper;
import com.stylefeng.guns.modular.system.warpper.StudentInfoWarpper;
import com.stylefeng.guns.modular.system.warpper.UserWarpper;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.stylefeng.guns.modular.system.model.BizStudentinfo;
import com.stylefeng.guns.modular.stuinfo.service.IBizStudentinfoService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 录量管理控制器
 *
 * @author fengshuonan
 * @Date 2018-09-21 14:42:19
 */
@Controller
@RequestMapping("/bizStudentinfo")
public class BizStudentinfoController extends BaseController {

    private String PREFIX = "/stuinfo/bizStudentinfo/";

    @Autowired
    private IBizStudentinfoService bizStudentinfoService;

    /**
     * 跳转到录量管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "bizStudentinfo.html";
    }

    /**
     * 跳转到添加录量管理
     */
    @RequestMapping("/bizStudentinfo_add")
    public String bizStudentinfoAdd() {
        return PREFIX + "bizStudentinfo_add.html";
    }

    /**
     * 跳转到修改录量管理
     */
    @RequestMapping("/bizStudentinfo_update/{bizStudentinfoId}")
    public String bizStudentinfoUpdate(@PathVariable Integer bizStudentinfoId, Model model) {
        BizStudentinfo bizStudentinfo = bizStudentinfoService.selectById(bizStudentinfoId);
        model.addAttribute("item",bizStudentinfo);
        LogObjectHolder.me().set(bizStudentinfo);
        return PREFIX + "bizStudentinfo_edit.html";
    }

    /**
     * 获取录量管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition, String beginTime, String endTime) {
        Page<BizStudentinfo> page = new PageFactory<BizStudentinfo>().defaultPage();
        List<Map<String, Object>> list = bizStudentinfoService.selectStudentinfo(page, condition, beginTime, endTime,page.getOrderByField(), page.isAsc());
        page.setRecords((List<BizStudentinfo>) new StudentInfoWarpper(list).warp());
        return super.packForBT(page);
    }

    /**
     * 新增录量管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(BizStudentinfo bizStudentinfo) {
        EntityWrapper<BizStudentinfo> wrapper = new EntityWrapper<>();
        String studentPhone = bizStudentinfo.getStudentPhone();
        String studentName = bizStudentinfo.getStudentName();
        // 如果输入的电话号码长度不足11位，则验证学生姓名和电话号码组合的重复性
        if(studentPhone.length() < 11 && studentName.length() > 0){
            wrapper.eq("studentName", studentName);
        }
        wrapper.eq("studentPhone", studentPhone);
        if (bizStudentinfoService.selectCount(wrapper) > 0) {
            return new ErrorTip(-1, "联系11位电话出现重复！<br/>或录入7位电话号码+姓名组合出现重复!");
        }

        ShiroUser currentUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        bizStudentinfo.setOwnerID(currentUser.getId()); // 录入人
        bizStudentinfo.setCreateDateTime(new Date());   // 录入时间
        bizStudentinfo.setIsValid(0);                   // 未核实信息
        bizStudentinfo.setIsDist(0);                    // 未联系或接待
        bizStudentinfoService.insert(bizStudentinfo);
        return SUCCESS_TIP;
    }

    /**
     * 删除录量管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer bizStudentinfoId) {
        BizStudentinfo bizStudentinfo = bizStudentinfoService.selectById(bizStudentinfoId);
        ShiroUser currentUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();

        // 只能删除自己创建的记录
        if(bizStudentinfo.getOwnerID() == currentUser.getId()) {
            // 只能删除新创建10分钟内的记录
            if (new Date().getTime() < bizStudentinfo.getCreateDateTime().getTime() + 600000) {
                bizStudentinfoService.deleteById(bizStudentinfoId);
                return SUCCESS_TIP;
            } else {
                return new ErrorTip(-1, "只能删除10分钟内新添加的记录!");
            }
        }else{
            return new ErrorTip(-2, "只能删除当前用户[" + currentUser.getName() + "]创建的记录!");
        }
    }

    /**
     * 修改录量管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(BizStudentinfo bizStudentinfo) {
        bizStudentinfoService.updateById(bizStudentinfo);
        return SUCCESS_TIP;
    }

    /**
     * 录量管理详情
     */
    @RequestMapping(value = "/detail/{bizStudentinfoId}")
    @ResponseBody
    public Object detail(@PathVariable("bizStudentinfoId") Integer bizStudentinfoId) {
        return bizStudentinfoService.selectById(bizStudentinfoId);
    }

    /**
     * 验证电话号码和姓名组合是否重复
     */
    @RequestMapping(value = "/validate_1")
    @ResponseBody
    public Object validateNameAndPhone(String studentName, String studentPhone){
        Map<String,Boolean> result = new HashMap<String, Boolean>(){{
            put("valid", false);
        }};

        // 任意条件为空则不进行验证，直接通过
        if(ToolUtil.isEmpty(studentPhone)){
            result.put("valid", true);
        }else {
            EntityWrapper<BizStudentinfo> wrapper = new EntityWrapper<>();
            // 如果输入的电话号码长度不足11位，则验证学生姓名和电话号码组合的重复性
            if(studentPhone.length() < 11 && studentName.length() > 0){
                wrapper.eq("studentName", studentName);
            }
            wrapper.eq("studentPhone", studentPhone);
            if (bizStudentinfoService.selectCount(wrapper) == 0) {
                result.put("valid", true);
            }
        }
        return result;
    }
}
